package com.magic233.timingTask;

import com.alibaba.fastjson.JSON;
import com.magic233.entity.AccessTokenAndExpiresIn;
import com.magic233.utils.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.SimpleDateFormat;
import java.util.Date;

@Configuration
@EnableScheduling
public class TimingTask {
    private static final Logger logger = LoggerFactory.getLogger(TimingTask.class);

    public static String accessToken = "";
    public static String lastUpdateTime = "";
    private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Value("${weixin.appid}")
    private String appid;

    @Value("${weixin.secret}")
    private String secret;

    @Async
    @Scheduled(fixedDelay = 1000 * 60 * 60)
    public void updateAccessToken() {

        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
        String re = HttpUtil.doGet(url);

        AccessTokenAndExpiresIn accessTokenAndExpiresIn = null;
        try {
            accessTokenAndExpiresIn = JSON.parseObject(re, AccessTokenAndExpiresIn.class);
        } catch (Exception e) {
            logger.warn("获取accessToken出错");
        }
        if (accessTokenAndExpiresIn != null) {
            if (accessTokenAndExpiresIn.getAccessToken() != null) {
                accessToken = accessTokenAndExpiresIn.getAccessToken();
                Long time = new Date().getTime();
                lastUpdateTime = simpleDateFormat.format(time);

                logger.info(accessToken);
                logger.info(lastUpdateTime);
            }
        }


    }


}
